package com.jingli.pile.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jingli.pile.configuration.PushProperties;
import com.jingli.pile.entity.PlatformInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PlatformCheckService implements UserDetailsService {
    @Autowired
    private PlatformInfoService platformInfoService;
    @Autowired
    private PushProperties pushProperties;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<PlatformInfo> platformInfoQueryWrapper = new QueryWrapper<>();
        platformInfoQueryWrapper.eq("platform_id",username);
        platformInfoQueryWrapper.eq("env",pushProperties.getEnv());
        PlatformInfo platformInfo = platformInfoService.getOne(platformInfoQueryWrapper);
        if (null!=platformInfo){
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("platform"));
            return new User(platformInfo.getPlatformId(), platformInfo.getPlatformSecret(),authorities);
        }else {
            throw new UsernameNotFoundException("用户:"+username+"不存在");
        }
    }
}
